# when pattern = "all", move all pattern of the same group, method and Pversion to tableto
transferOrderLogicDb <- function(tablefrom, tableto, group, pattern, method="fixedPct1", direction="long", Pversion=0, execute=FALSE) {
  selectSqlString <- function(table) {
    sql <- sprintf("SELECT * FROM `%s` WHERE 
                   `group` = '%s' AND 
                   `pattern` = '%s' AND
                   `method` = '%s' AND
                   `direction` = '%s' AND
                   `Pversion` = %d", table, group, pattern, method, direction, Pversion)
    return (sql)
  }
  # select all of same group, method, Pversion
  selectAllSqlString <- function(table) {
    sql <- sprintf("SELECT * FROM `%s` WHERE 
                   `group` = '%s' AND 
                   `method` = '%s' AND
                   `Pversion` = %d", table, group, method, Pversion)
    return (sql)
  }  
  insertSqlString <- function(table, df) {
    sql <- sprintf("INSERT INTO `va_stratlab`.`%s` 
                   (`id`, `group`, `pattern`, `symbol`, `Pversion`, `method`, `entry`,
                   `stoplosslimit`, `stopwinlimit`, `direction`, `duration`, 
                   `numberoftrades`, `pctstopped`, `stoplosspct`, `stopwinpct`, 
                   `returnmean`, `returnsd`, `returnddev`, `pctwin`)", table)
    values <- sprintf("VALUES
                      (NULL, '%s', '%s', '%s', '%d', '%s', '%s',
                      '%f', '%f', '%s', '%f',
                      '%f', '%f', '%f', '%f', 
                      '%f', '%f', '%f', '%f')",
                      group, df["pattern"], "", Pversion, method, df["entry"], 
                      df["stoplosslimit"], df["stopwinlimit"], df["direction"], df["duration"],
                      df["numberoftrades"], df["pctstopped"], df["stoplosspct"], 
                      df["stopwinpct"], df["returnmean"], df["returnsd"],
                      df["returnddev"], df["pctwin"])
    return (paste(sql, values))
  }
  con <- connectToVadb()
  if (pattern=="all") {
    transfervalues <- dbGetQuery(con, selectAllSqlString(tablefrom))
    destinationvalues <- dbGetQuery(con, selectAllSqlString(tableto))   
  } else {
    transfervalues <- dbGetQuery(con, selectSqlString(tablefrom))
    destinationvalues <- dbGetQuery(con, selectSqlString(tableto))
  }
  
  cat ("to move:", dim(transfervalues)[1], ". already in target db:", dim(destinationvalues)[1], "\n")
  if (pattern!="all" & dim(destinationvalues)[1] > 0) {
    stop ("destination table contains values of same kind.")
  } else if (execute==FALSE) {
    stop ("execute is false")
  } else if (execute==TRUE) {
    cat ("now copy entries to destination table\n")
    for (i in 1:dim(transfervalues)[1]) {
      #return(insertSqlString(tableto, transfervalues[i,]))
      dbSendQuery(con, insertSqlString(tableto, transfervalues[i,]))
    }
  }
  dbDisconnect(con)
  #return(transfervalues)
}